const mysql = require("mysql");

let sql;
module.exports = (req, res) => {
    // 允许任何前端跨域访问我
    res.setHeader("access-control-allow-origin", "*");

    switch (true) {
        // 获取全部省份信息
        case req.url === "/china/province/0":
            var connection = mysql.createConnection({
                host: "localhost",
                user: "root",
                password: "123456",
                database: "china",
            });
            connection.connect();

            sql = `select * from t_province;`;
            connection.query(sql, (err, results) => {
                res.end(JSON.stringify({ err, results }));
            });
            break;

        // 获取特定省份详情
        /* 
        {
            proid:19,
            cities:{
                190:{
                    name:"广州市",
                    cityid:190,
                    districts:[{"白云区"},{"天河区"}...]
                },
                ...
            }
        }        
        */
        case req.url.startsWith("/china/province/"):
            // 揪出省份id
            const regProid = /province\/(\d+)/;
            const proid = regProid.exec(req.url)[1];

            var connection = mysql.createConnection({
                host: "localhost",
                user: "root",
                password: "123456",
                database: "china",
            });
            connection.connect();

            let provinceDetail = {
                proid,
                cities: {},
            };

            // 查询所有地级市
            new Promise((resolve, reject) => {
                sql = `select * from t_city where ProID = ${proid};`;
                connection.query(sql, (err, results) => {
                    if (!err && results.length) {
                        resolve(results);
                    } else {
                        reject({ msg: "查询地级市错误", err, results });
                    }
                });
            })

                // 处理地级市数据
                .then((cities) => {
                    cities.forEach((c) => {
                        provinceDetail.cities[c.CityID] = c;
                    });
                })

                // 查询区县数据
                .then((value) => {
                    return new Promise((resolve, reject) => {
                        sql = `select * from t_district where CityID in (
                            select CityID from t_city where ProID = ${proid}
                        );`;
                        connection.query(sql, (err, results) => {
                            if (!err && results.length) {
                                resolve(results);
                            } else {
                                reject({
                                    msg: "请求区县数据时发生错误",
                                    err,
                                    results,
                                });
                            }
                        });
                    });
                })

                // 处理区县数据
                .then((districts) => {
                    districts.forEach((d) => {
                        // 初始化城市的districts
                        provinceDetail.cities[d.CityID].districts =
                            (provinceDetail.cities[d.CityID].districts || []);

                        // 将当前区县插入其所在城市的districts数组
                        provinceDetail.cities[d.CityID].districts.push(d);
                    });

                    // 至此，全部省份详情组装完毕
                })

                // 返回完整数据给前端
                .then(() => {
                    res.end(JSON.stringify({code:1,provinceDetail}))
                })

                // 处理环节错误
                .catch((err) => res.end(JSON.stringify({code:-1,err})));

            break;

        default:
            res.end("404");
            break;
    }
};
